package org.zfes.snowier.cloud.zbss.metting.biz.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZDateUtil;
import org.zfes.snowier.core.util.ZObjectUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.common.dao.params.ParamMap;
import org.zfes.snowier.cloud.zbss.metting.biz.service.ISignupInfoService;
import org.zfes.snowier.cloud.zbss.metting.biz.service.ISignupModelService;
import org.zfes.snowier.cloud.zbss.metting.biz.service.ISignupService;
import org.zfes.snowier.cloud.zbss.metting.biz.dao.SignupMapper;
import org.zfes.snowier.cloud.zbss.metting.biz.dto.SignupInfoDto;
import org.zfes.snowier.cloud.zbss.metting.biz.model.Signup;
import org.zfes.snowier.cloud.zbss.metting.biz.model.SignupInfo;
import org.zfes.snowier.cloud.zbss.metting.biz.model.SignupModel;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.zfes.snowier.cloud.zbss.metting.biz.dto.SignupModelJsonDto;
@Service
public class SignupServiceImpl implements ISignupService{
 	@Autowired
	private SignupMapper signupMapper;
 	@Autowired
	private ISignupInfoService signupInfoService;
	@Autowired
	private ISignupModelService signupModelService;
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadSignupDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		if(!pm.getLong("metId").isPresent()) {
			return DataSet.emptyDS();
		}
		Long count=signupMapper.selectListCount(pm);
		if(ZObjectUtil.isNull(count)||count==0L) {
			return DataSet.emptyDS();
		}
		List<Signup>  signupList = signupMapper.selectModelListPage(pm);
		
		List<SignupInfo> signupInfoList = signupInfoService.loadBySignupIdList(signupList.stream().map(val->val.getId()).collect(Collectors.toList()));
		
		List<Map<String,Object>> rows=signupList.stream().map(signup->{
					//找到某个人的报名数据项列表
					List<SignupInfo> oneSignupInfoList = signupInfoList.stream().filter(si -> signup.getId().equals(si.getSignupId())).collect(Collectors.toList());
					//报名数据转化成  //key:FieldName  ,value: FieldValue
					Map<String,String> oneSignupInfoMapStr = oneSignupInfoListToMap(oneSignupInfoList);
					
					//Collectors.toMap 报名数据转化成  //key:FieldName  ,value: FieldValue==Object
					Map<String,Object> oneSignupInfoMapObj = oneSignupInfoMapStr.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
					oneSignupInfoMapObj.put("id", signup.getId());
					 return oneSignupInfoMapObj;
			 
				}).collect(Collectors.toList());
		
		DataSet ds=DataSet.newDS(count, rows);
		return ds;
	}
	//key:FieldName  ,value: FieldValue
	private Map<String,String> oneSignupInfoListToMap(List<SignupInfo> oneSignupInfoList){
		Map<String,String> signupInfoMap = oneSignupInfoList.stream().collect(Collectors.toMap(SignupInfo::getFieldName, 
				signupInfo->{return ZStrUtil.hasText(signupInfo.getFieldValue())?signupInfo.getFieldValue():signupInfo.getFieldValueText();} ));
		return signupInfoMap;
	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<SignupInfoDto> loadSignup(Long metId,Long signupId) {
		if(metId==null||signupId==null) {
			return Lists.newArrayList();
		}
		List<SignupModelJsonDto> amodelList= signupModelService.loadAmodelListByMetId( metId);
 	
 		List<SignupInfo> signupInfoList =	signupInfoService.loadBySignupId(signupId);
 		
 		if(ZObjectUtil.isEmpty(signupInfoList)) {
 			return Lists.newArrayList();
 		}
 		
 		//key:FieldName  ,value: FieldValue
 		Map<String,String> signupInfoMap = oneSignupInfoListToMap(signupInfoList);
 		
 		List<SignupInfoDto> signupInfoDtoList=Lists.newArrayList();
 		for(SignupModelJsonDto amodel: amodelList) {
 			String type=amodel.getType();
 			String value="";
 			switch (type) {
			case "text":
				value=signupInfoMap.get(amodel.getName());
				break;
			case "textarea":
				value=signupInfoMap.get(amodel.getName());
				break;
			case "number":
				value=signupInfoMap.get(amodel.getName());
				break;
			case "date":
				value=signupInfoMap.get(amodel.getName());
				break;
			case "file":
				value=signupInfoMap.get(amodel.getName());
				break;
			case "checkbox-group":
				value=getOpLables( amodel, signupInfoMap);
				break;
			case "select":
				value=getOpLables( amodel, signupInfoMap);
				break;
			case "radio-group":
				value=getOpLables( amodel, signupInfoMap);
			default:
				break;
			}
 			SignupInfoDto signupInfoDto=new SignupInfoDto()
		 			.setLabel(amodel.getLabel())
		 			.setName(amodel.getName())
		 			.setType(amodel.getType())
		 			.setSubtype(amodel.getSubtype())
		 			.setValue(value);
 			signupInfoDtoList.add(signupInfoDto);
 			
 		}
 		return signupInfoDtoList;
		
	}
	
	private String getOpLables(SignupModelJsonDto amodel,Map<String,String> signupInfoMap) {
		Map<String, String> opValues=amodel.getValues();
		String ops=signupInfoMap.get(amodel.getName());
		String opLabels="";
		if(ZStrUtil.hasText(ops)) {
			String[] opArray=ops.split(",");
			for(String str: opArray) {
				opLabels+=opValues.get(str)+",";
			}
		}
		return opLabels;
	}
	
	 	@Transactional(rollbackFor=Exception.class)
	 	@Override
		public void  createSignup(Long metId, Map<String, Object> params) {
	 		Signup signup=new Signup().setMetId(metId)
	 				.setPayStatus(Byte.valueOf("1")).setStatus(Byte.valueOf("1"))
	 				.setSignupTime(ZDateUtil.newDate());
	 		
	 		ZBeanUtil.setCreateInfo(signup);
			ZBeanUtil.validateBean(signup);
			signupMapper.insertSelective(signup);
	 		Long signupId=signup.getId();
	 		
	 		signupInfoService.createSignupInfo(metId, signupId, params);
	 		
		}
 
 	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<Signup> loadSignupById(Long signupId){
 		if(signupId==null) {
			return Optional.empty();
		}
 		Signup signup=signupMapper.selectByPrimaryKey(signupId);
 		return Optional.ofNullable(signup);
 	}
 	
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateSignup(Signup signup) {
		ZBeanUtil.setUpdatedInfo(signup);
		ZBeanUtil.validateBean(signup);
		signupMapper.updateByPrimaryKeySelective(signup);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteSignup(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		signupMapper.deleteByPrimaryKey(id);
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setSignupStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		signupMapper.updateStatus( id,  status) ;
	}

	
	

	
}